﻿using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Threading;
using System.Windows.Forms;

namespace H.Driver.Server
{
    /// <summary>
    /// APP入口
    /// </summary>
    public class App : IApp
    {
        private static readonly ManualResetEvent ShutdownEvent = new ManualResetEvent(false);

        /// <summary>
        /// 是否已经初始化通道
        /// </summary>
        private static bool _HadInit = false;

        /// <summary>
        /// 初始化通道
        /// </summary>
        private static void InitChannel()
        {
            if (!_HadInit)
            {
                ChannelServices.RegisterChannel(new TcpClientChannel(), false);
                _HadInit = true;
            }
        }

        /// <summary>
        /// 显示帮助信息
        /// </summary>
        private static void DisplayHelper()
        {
            MessageBox.Show("Usage: <app> [[/port=PORT] [/shutdown|/restart] [/quit]|/?]");
        }

        public static void Main(string[] args)
        {
            int port = 7754;    //默认服务器端口即是这个
            bool quit = false;

            foreach (string arg in args)
            {
                if (string.IsNullOrEmpty(arg))
                {
                    continue;
                }
                string[] pieces = arg.Split('=');
                switch (pieces[0].ToLower())
                {
                    case "port":
                        {
                            if (pieces.Length > 1 && int.TryParse(pieces[1], out int tmpPort))
                            {
                                port = tmpPort;
                            }
                            break;
                        }
                    case "/shutdown":
                        {
                            InitChannel();
                            try
                            {
                                RemoteController controller = Activator.GetObject(typeof(RemoteController), $"tcp://127.0.0.1:{port}/sys") as RemoteController;
                                controller.ShutDownServer();
                            }
                            catch (Exception) { }
                            return;
                        }
                    case "/restart":
                        {
                            InitChannel();
                            try
                            {
                                RemoteController controller = Activator.GetObject(typeof(RemoteController), $"tcp://127.0.0.1:{port}/sys") as RemoteController;
                                controller.ShutDownServer();
                            }
                            catch (Exception) { }
                            break;
                        }
                    case "/quit":
                        {
                            quit = true;
                            break;
                        }
                    case "/?":
                        {
                            DisplayHelper();
                            return;
                        }
                }
            }

            RemoteController.ShutDown += RemoteController_ShutDown;

            try
            {
                TcpServerChannel channel = new TcpServerChannel(port);
                ChannelServices.RegisterChannel(channel, false);

                RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingEyeFactory), "eye", WellKnownObjectMode.Singleton);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingHandFactory), "hand", WellKnownObjectMode.Singleton);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteController), "sys", WellKnownObjectMode.Singleton);

                if (!quit)
                {
                    MessageBox.Show("驱动服务器已启动,监听端口为:" + port);
                }

                ShutdownEvent.WaitOne();
            }
            catch (Exception err)
            {
                MessageBox.Show("启动服务器失败,可能服务器已经启动,错误原因:\r\n" + err.Message);
            }
        }

        private static void RemoteController_ShutDown(object sender, EventArgs e)
        {
            ShutdownEvent.Set();
        }
    }
}
